package com.lyq.leetcode.字符串解码394;

import java.util.Arrays;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        System.out.println(main.decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }

    /**
     * a-z:97-122
     * 0-9:48-57
     * []:91|93
     *
     * @param s
     * @return
     */
    public String decodeString(String s) {
        Stack<Character> stack = new Stack<>();
        char[] charArray = s.toCharArray();
        for (char ch : charArray) {
            if (ch == 93) {
                boolean flag = false;
                StringBuilder temp = new StringBuilder();
                StringBuilder tempK = new StringBuilder();
                while (!stack.empty()) {
                    Character pop = stack.pop();
                    if (pop >= 48 && pop <= 57) {
                        tempK.insert(0, pop);
                    } else if (pop >= 97 && pop <= 122) {
                        if (flag) {
                            stack.push(pop);
                            break;
                        }
                        temp.insert(0, pop);
                    } else if (pop == 91) {
                        if (flag) {
                            stack.push(pop);
                            break;
                        }
                        flag = true;
                    }
                }
                int k =1;
                if (!tempK.isEmpty()){
                    k =Integer.parseInt(tempK.toString());
                }
                String str =temp.toString();
                String repeated = str.repeat(k);
                char[] charArray1 = repeated.toCharArray();
                for (char c:charArray1){
                    stack.push(c);
                }
            } else {
                stack.push(ch);
            }
        }
        StringBuilder res = new StringBuilder();
        Character[] array = stack.toArray(new Character[0]);
        for (Character c:array){
            res.append(c);
        }
        return res.toString();
    }
}
